/*
 * Copyright 2008 Zoundry LLC, Inc.  All Rights Reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 */
package org.zoundry.gaedt.core.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.content.IContentType;
import org.eclipse.ui.IEditorDescriptor;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorRegistry;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.part.FileEditorInput;
import org.zoundry.gaedt.core.ZGaeCoreActivator;
import org.zoundry.gaedt.core.ZGaeException;


/**
 * Some static utility methods that assist in dealing with Eclipse resources.
 */
public final class ZGaeResourceUtil
{
    /**
     * Private util class c'tor.
     */
    private ZGaeResourceUtil()
    {
    }
    
    /**
     * Gets the contents of an input stream as a String.
     * 
     * @param aInputStream
     * @param aCharset
     * @throws ZGaeException
     */
    public static String getContents(InputStream aInputStream, String aCharset) throws ZGaeException
    {
        BufferedReader reader = null;
        try
        {
            reader = new BufferedReader(new InputStreamReader(aInputStream, aCharset));
            StringBuffer buffer = new StringBuffer();
            synchronized (buffer)
            {
                String str = null;
                while ((str = reader.readLine()) != null)
                {
                    buffer.append(str);
                    buffer.append("\r\n"); //$NON-NLS-1$
                }
                return buffer.toString();
            }
        }
        catch (Exception e)
        {
            throw new ZGaeException(e);
        }
        finally
        {
            ZGaeCloser.close(reader);
        }
    }

    /**
     * Returns the contents of the given file as a String.
     *
     * @param aFile
     */
    public static String getContents(IFile aFile) throws ZGaeException
    {
        try
        {
            aFile.refreshLocal(IResource.DEPTH_ZERO, null);
            InputStream iStream = aFile.getContents();
            String charset = aFile.getCharset();
            return getContents(iStream, charset);
        }
        catch (Exception e)
        {
            throw new ZGaeException(e);
        }
    }

    /**
     * Returns a {@link Reader} over the given {@link IFile}.
     *
     * @param aFile
     */
    public static Reader getReader(IFile aFile) throws ZGaeException
    {
        try
        {
            aFile.refreshLocal(IResource.DEPTH_ZERO, null);
            return new InputStreamReader(aFile.getContents(), aFile.getCharset());
        }
        catch (Exception e)
        {
            throw new ZGaeException(e);
        }
    }

    /**
     * Utility method which attempts to find the appropriate editor type for the
     * passed file and open it.
     * 
     * @param aFile
     * @throws ZGaeException
     */
    public static IEditorPart openEditor(IFile aFile) throws ZGaeException
    {
        return openEditor(aFile, null);
    }

    /**
     * Utility method which attempts to find the appropriate editor type for the
     * passed file and open it.
     *
     * @param aFile
     * @param aDefaultEditorId
     * @throws ZGaeException
     */
    public static IEditorPart openEditor(IFile aFile, String aDefaultEditorId) throws ZGaeException
    {
        String defaultEditorId = aDefaultEditorId;
        if (defaultEditorId == null)
            defaultEditorId = IEditorRegistry.SYSTEM_EXTERNAL_EDITOR_ID;
        IEditorPart editorPart = null;
        IWorkbenchWindow window = ZGaeUtil.getActiveWorkbenchWindow();
        if (aFile.exists() && window != null)
        {
            IWorkbenchPage page = window.getActivePage();
            if (page != null)
            {
                IContentType contentType = null;
                try
                {
                    aFile.refreshLocal(IResource.DEPTH_ZERO, null);
                    if (aFile.getContentDescription() != null)
                        contentType = aFile.getContentDescription().getContentType();
                }
                catch (Exception ex)
                {
                    ZGaeUtil.logError(ex);
                }

                String editorId = defaultEditorId;
                IEditorRegistry editorRegistry = ZGaeCoreActivator.getDefault().getWorkbench().getEditorRegistry();
                if (contentType != null)
                {
                    IEditorDescriptor defaultEditor = editorRegistry.getDefaultEditor(aFile.getName(), contentType);
                    if (defaultEditor != null)
                        editorId = defaultEditor.getId();
                }
                else
                {
                    IEditorDescriptor defaultEditor = editorRegistry.getDefaultEditor(aFile.getName());
                    if (defaultEditor != null)
                        editorId = defaultEditor.getId();
                }

                try
                {
                    editorPart = page.openEditor(new FileEditorInput(aFile), editorId);
                }
                catch (PartInitException ex)
                {
                    throw new ZGaeException(ex);
                }
            }
        }
        return editorPart;
    }
}
